import plugin from '../../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import fs from 'node:fs'


export class avSearch extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: '搜老师',
            /** 功能描述 */
            dsc: '通过截图搜索不认识的老师名字',
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 1002,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: '#*搜老师$',
                    /** 执行方法 */
                    fnc: 'avSearch'
                }
            ]
        })
    }

    /**
     * 
     */
    async avSearch(e) {

        if (this.e.source) {
            let reply;
            if (this.e.isGroup) {
                reply = (await this.e.group.getChatHistory(this.e.source.seq, 1)).pop()?.message;
            } else {
                reply = (await this.e.friend.getChatHistory(this.e.source.time, 1)).pop()?.message;
            }
            if (reply) {
                for (let val of reply) {
                    if (val.type == "image") {
                        this.e.img = [val.url];
                        break;
                    }
                }
            }
        }

        if (!this.e.img) {

            this.setContext('dealImg');
            await this.reply(" 请发送人脸截图", false, { at: true });
        }else{
            this.dealImg();
        }

    }
    async dealImg() {

        if (!this.e.img) {
            return true;
        }

        let responseImage = await fetch(this.e.img[0]);
        if (!responseImage.ok) {
            await this.reply("获取图片失败", false, { at: true });
        }

        let buffer = await responseImage.arrayBuffer();
        let headers = {
            "Content-Type": "image/jpeg"
        };
        let file = Buffer.from(buffer, 'binary');
        let urlapi = "https://xslist.org/search/pic";
        let response = await fetch(urlapi, { method: "POST", body: file, headers });
        let res = await response.json();

        this.e.reply("嘿嘿，还没做完，摆了");
        console.log(res);

        this.finish('dealImg');
    }
}